package com.atguigu.gmall.mq.service.impl;

import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.mq.service.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.time.Duration;

@Slf4j
public class RabbitServiceImpl implements RabbitService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendMsg(String exchange, String routeKey, Object msg) {

        rabbitTemplate.convertAndSend(exchange, routeKey, JSONs.objecttoString(msg));
    }

    @Override
    public void retry(long deliveryTag, Channel channel, String json, int retryCount) throws IOException {
        String encrypt = MD5.encrypt(json);
        Long increment = stringRedisTemplate.opsForValue().increment(RedisConstant.REDIS_RETRY_COUNT + encrypt);
        stringRedisTemplate.expire(RedisConstant.REDIS_RETRY_COUNT + encrypt, Duration.ofSeconds(5));
        if (increment <= retryCount) {
            log.info("第{}次重试中...,消息为：{}", increment, json);
            channel.basicNack(deliveryTag,false,true);
        }else {
            channel.basicAck(deliveryTag, false);
            log.info("重试{}次失败，存入数据库，人工介入",retryCount);
        }
    }
}
